package com.ruyuan2020.furnishing.common.config;

import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository;
import com.alibaba.cloud.dubbo.registry.event.ServiceInstancesChangedEvent;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class DubboSubscriptionConfig implements ApplicationListener<ApplicationReadyEvent> {

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        DubboServiceMetadataRepository dubboServiceMetadataRepository = applicationReadyEvent.getApplicationContext().getBean(DubboServiceMetadataRepository.class);
        Set<String> subscribedServices = dubboServiceMetadataRepository.getSubscribedServices();
        if (!ObjectUtils.isEmpty(subscribedServices)) {
            DiscoveryClient DiscoveryClient = applicationReadyEvent.getApplicationContext().getBean(DiscoveryClient.class);
            for (String subscribedService : subscribedServices) {
                ServiceInstancesChangedEvent changedEvent = new ServiceInstancesChangedEvent(subscribedService, DiscoveryClient.getInstances(subscribedService));
                applicationReadyEvent.getApplicationContext().publishEvent(changedEvent);
            }
        }
    }
}
